#!/usr/bin/env python

import os, sys, socket, random, select, string, struct, datetime, time, signal, threading


# setup win32 for on-the-fly importing
if sys.platform == "win32":
	path = sys.path[0]

	path = path.replace("\\", "/")

	path = os.path.dirname(path + "/")

	path = path.replace("/", "\\")

	sys.path.append(path + "\\plugins")

	sys.path.append(path + "\\protocols")

import config

from libs.dae.event import EventDispatcher

if config.isCommand("realm"):
	config.realm = socket.gethostbyname(config.isCommand("realm"))
else:
	config.realm = socket.gethostbyname("uswest.battle.net")

class GreenVex(EventDispatcher):
	def __init__(self):
		EventDispatcher.__init__(self, "Invalidate")
		
		self.plugins = []
	
	def main(self):
		# wait for gui to load
		time.sleep(1)
		
		if config.isCommand("plugins"):
			plugins = config.isCommand("plugins").split(",")
		else:
			plugins = ("server", "proxy")
		
		for plugin in plugins:
			mod = __import__(plugin, globals(), locals(), ['*'])
			
			if mod.main:
				self.addPlugin(mod.main())
		
		while(True):
		    self.Invalidate()
		    
		    time.sleep(0.1)
	
	def addPlugin(self, plugin):
		self.plugins.append(plugin)
		
		plugin.initialize(self)


def quit(*a):
	print "Quitting..."

	time.sleep(5000) # show the quit message

	raise SystemExit(0)

signal.signal(signal.SIGINT, quit)

if __name__ == "__main__":
	greenvex = GreenVex()
	
	thread = threading.Thread(target=greenvex.main)
	thread.setDaemon(True)
	thread.start()
	
	if config.gui:
		import gui
		
		gui.app = gui.Application(redirect=True)
		gui.app.MainLoop()